package main

import (
	"io"
	"os"
)

/*
复制文件
*/
func main() {
	srcFile := "srcFile"
	tarFile := "ab.txt"

	// 方法1
	CopyFile(srcFile, tarFile)

	// 方法2
	CopyFile2(srcFile, tarFile)

	// 方法3
	//通过ioutil.ReadFile, ioutil.writeFile
}

func CopyFile2(srcFile, destFile string) (int64, error) {
	src, err := os.Open(srcFile)
	if err != nil {
		return 0, err
	}
	tar, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		return 0, err
	}
	defer src.Close()
	defer tar.Close()
	return io.Copy(tar, src)
}

func CopyFile(srcFile, destFile string) (int, error) {
	src, err := os.Open(srcFile)
	if err != nil {
		return 0, err
	}
	tar, err := os.OpenFile(destFile, os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		return 0, err
	}
	defer src.Close()
	defer tar.Close()

	bs := make([]byte, 1024, 1024)
	n := -1
	total := 0
	for {
		n, err = src.Read(bs)
		if err == io.EOF || n == 0 {
			break
		} else if err != nil {
			return total, err
		}
		total += n
		_, err = tar.Write(bs[:n])
		if err != nil {
			return total, err
		}
	}
	return total, nil
}
